<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form
        :inline="true"
        :model="formSearch"
        size="small"
        style="display: flex; justify-content: space-between"
      >
        <div>
          <el-form-item>
            <BackButton pages="/GoodsList" />

            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="handleAdd('', 1)"
              v-show="permission.add"
              >添加分类</el-button
            >
          </el-form-item>
        </div>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="分类">
          <template slot-scope="scope">
            <div class="rowBox">
              <span class="weckName">{{ scope.row.name }}</span>
              <img
                v-if="scope.row.parentId != 0"
                style="width: 40px; height: 40px; margin-top: -8px"
                :src="scope.row.picture"
                alt=""
              />
              <span v-if="scope.row.parentId != 0"
                >{{ scope.row.goodsNumber }}&nbsp;&nbsp;种商品</span
              >
            </div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="480" align="center">
          <template slot-scope="scope">
            <el-button
              size="medium "
              @click="handleAdd(scope.row, 2)"
              v-if="scope.row.parentId == 0 && permission.addChidren"
              >添加子分类</el-button
            >

            <el-button
              type="primary"
              size="medium "
              @click="handleEdit(scope.row)"
              v-if="permission.edit"
              >编辑</el-button
            >

            <el-button
              type="danger"
              size="medium "
              @click="handleDel(scope.row.id)"
              v-if="permission.del"
              >删除</el-button
            >
            <!-- <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-if="scope.row.type==2&&permission.del"
            >删除页面</el-button> -->
            <!-- <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-if="scope.row.type==3&&permission.del"
            >删除按钮</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 权限添加和权限编辑 -->
      <el-dialog
        :title="type === 'add' ? '添加分类' : '修改分类'"
        :visible.sync="visible"
        @close="onCancel('ruleForm')"
        width="550px"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          size="mini"
          label-width="120px"
        >
          <el-form-item
            label="分类名称"
            prop="node_name"
            style="margin-bottom: 30px"
          >
            <el-input
              :maxlength="ruleForm.type == 1 ? '7' : ''"
              clearable
              v-model="ruleForm.node_name"
              placeholder="请输入分类名称"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.type == '2'"
            label="图片"
            prop="image"
            style="margin-bottom: 30px"
            :rules="{
              required: true,
              message: '请选择图片',
              trigger: 'blur',
            }"
          >
            <UploadImage
              @getImgSrc="getImgSrc"
              :imageUrl.sync="ruleForm.image"
              ref="image"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="onCancel('ruleForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onConfirm('ruleForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  goodsTypeList,
  typeAdd,
  typeEdit,
  typeDel,
  MAIN,
} from "../../utils/api";
import BackButton from "../../components/BackButton";
import UploadImage from "../../components/UploadImage";
export default {
  name: "AuthMenu",
  props: ["height"],
  components: {
    UploadImage,
    BackButton,
  },
  data() {
    return {
      tableData: [],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      permission: {
        add: false,
        edit: false,
        del: false,
        addChidren: false,
      }, //权限
      formSearch: {
        role_name: "",
      }, //搜索
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        node_name: "",
        node_url: "",
        sort: "",
        type: "",
        image: "",
      }, //添加和修改的表单
      rules: {
        node_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
        node_url: [
          { required: true, message: "请选择图片", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        // type: [{ required: true, message: "请选择排序", trigger: "change" }]
      },
    };
  },

  mounted() {
    this.getResource();
  },
  methods: {
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增 85
      // 修改 86
      // 删除 87
      // 添加子分类
      if (arr.indexOf("26") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("27") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("28") > -1) {
        this.permission.del = true;
      }
      if (arr.indexOf("29") > -1) {
        this.permission.addChidren = true;
      }
      // addChidren

      this.getData();
    },
    //获取初始数据
    getData() {
      this.loading = true;
      //   let params = {
      //     role_name: this.formSearch.role_name,
      //     pageNumber: this.currentPage,
      //     pageSize: this.pageSize
      //   };
      this.postRequest(goodsTypeList, {}, MAIN).then((res) => {
        if (res.code == 200) {
          console.log(res);
          this.tableData = res.data;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd(row, k) {
      // k ==1 不显示列表类型 为菜单
      // k ==2 不显示列表类型 添加为页面
      // k ==3 不显示列表类型 添加为按钮
      this.ruleForm.type = k;
      this.type = "add";
      if (row) {
        this.currentRow = row;
        console.log(this.currentRow);
      } else {
        this.currentRow = {};
        console.log(this.currentRow);
      }
      this.visible = true;
    },
    getImgSrc(e) {
      this.ruleForm.image = e;
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      this.currentRow = row;
      this.visible = true;
      this.ruleForm = {
        node_name: row.name,
        image: row.picture,
        // f_id
        type: row.parentId == 0 ? "1" : "2",
      };
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.postRequest(typeDel, parm, MAIN).then((res) => {
            // console.log(res);
            if (res.code == 200) {
              this.$notify({
                title: "删除成功",
                message: res.msg,
                type: "success",
              });
              this.getData();
            }
          });
        })
        .catch(() => {});
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.menuAdd();
          } else if (this.type == "edit") {
            this.menuEdit();
          }
        } else {
          return false;
        }
      });
    },
    // 添加
    menuAdd() {
      console.log(this.ruleForm.type);
      let params = {
        name: this.ruleForm.node_name,
        picture: this.ruleForm.image,
      };
      if (this.ruleForm.type == 1) {
        params.parentId = 0;
      } else {
        params.parentId = this.currentRow.id;
      }

      this.postRequest(typeAdd, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "添加成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 编辑
    menuEdit() {
      let params = {
        id: this.currentRow.id,
        name: this.ruleForm.node_name,
        picture: this.ruleForm.image,
        parentId: this.currentRow.parentId,
      };

      this.postRequest(typeEdit, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "编辑成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.onReset();
    },
    //清空重置表单
    onReset() {
      this.visible = false;
      this.confirmLoading = false;
      if (this.$refs.image) this.$refs.image.clear();
      this.ruleForm = {
        node_name: "",
        node_url: "",
        type: 1,
        image: "",
      };
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
/deep/ .el-button--mini {
  padding: 7px 7px;
}
.tip {
  text-align: right;
  line-height: 30px;
  position: relative;
  color: red;
  font-size: 14px;
}
.rowBox {
  display: flex;
  position: absolute;
  top: 17px;
  width: 68%;
  font-size: 18px;
  justify-content: space-between;
  left: 100px;
}
.weckName {
  font-weight: bold;
  width: 51%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
